package com.bw.demo_mvi

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.demo_mvi.http.BaseResponse
import com.bw.demo_mvi.http.VideoEntity
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/16 14:49
 * @Description :
 */
class MainViewModel: ViewModel() {

    //通道:存储是意图
    val channel = Channel<MainIntent>(Channel.UNLIMITED)

    //热流：存储是状态，必须有默认的状态(本类中更新状态)
    private val _uiState = MutableStateFlow<MainUIState>(MainUIState.Loading)

    //不可变热流：需要将可变热流转成不可变热流(activity中获得状态)
    val uiState: StateFlow<MainUIState> = _uiState.asStateFlow()

    //处理意图
    init {
        handleIntent()
    }

    //处理意图：从通道中获得意图-》判断意图类型-》网络请求数据
    private fun handleIntent() {
        viewModelScope.launch {
            channel.consumeAsFlow().collect {
                when(it){
                    is MainIntent.GetVideo -> loadVideo(it.currentPage, it.pageSize)
                    is MainIntent.GetBanner -> loadBanner()
                }
            }
        }
    }

    //网络请求数据-》更新状态
    private fun loadVideo(currentPage: Int, pageSize: Int) {
        viewModelScope.launch {
            flow<BaseResponse<MutableList<VideoEntity>>> {
                val mainRepository = MainRepository()
                val video = mainRepository.getVideo(currentPage, pageSize)
                emit(video)
            }.catch {e->
                _uiState.value = MainUIState.Error(e.message.toString())
            }.filter {
                it != null
            }.collect {
                if (it.code == 200){
                    _uiState.value = MainUIState.Success(it.data)
                }else{
                    _uiState.value = MainUIState.Error(it.message)
                }
            }
        }
    }

    private fun loadBanner() {

    }

}